﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace MCSharpLib.MNet
{
    public class Downloader
    {
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="URI">网络地址</param>
        /// <param name="filename">文件存放地址</param>
        public static void DownLoadFile(string URI,string filename)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream downStream = response.GetResponseStream();
                BinaryReader br = new BinaryReader(downStream);
                if (File.Exists(filename))
                    File.Delete(filename);
                FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8);
                long finishChunk = 0;
                while (response.ContentLength > finishChunk)
                {
                    byte[] content;
                    if ((response.ContentLength - finishChunk) >= 1024)
                    {
                        content = br.ReadBytes(1024);
                        finishChunk += 1024;
                    }
                    else
                    {
                        content = br.ReadBytes((int)(response.ContentLength - finishChunk));
                        finishChunk += response.ContentLength - finishChunk;
                    }
                    bw.Write(content);
                }
                bw.Close();
                br.Close();
                fs.Close();
                //response.Dispose();
            }
            catch (Exception e)
            {
                throw e;
            }

        }
    }
}
